//
//  XTLoginController.swift
//  XTMuteOpen
//
//  Created by bushAK on 2024/1/22.
//

import UIKit
import WSProgressHUD
import Alamofire

class XTLoginController: XTBaseController {
    
    @IBOutlet weak var contentBgView: UIView!
    
    @IBOutlet weak var appNameLb: UILabel!
    
    
    @IBOutlet weak var phoneNumTf: UITextField!
    
    @IBOutlet weak var codeNumTf: UITextField!
    
    @IBOutlet weak var sendCodeBtn: UIButton!
    
    @IBOutlet weak var agreeImgV: UIImageView!
    
    
    var countDownTimer: Timer?
    var countDownNum = 60

    
    override func viewDidLoad() {
        super.viewDidLoad()

        if let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String {
            appNameLb.text = name
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
       
            self.contentBgView.applyRoundCorners(view: self.contentBgView, corners: [.topLeft, .topRight], radius: 16.0)

        })
        
        
    }
    
    
    @IBAction func sendCheckCodeClick(_ sender: UIButton) {
        if  ( phoneNumTf.text?.count ?? 0) == 0 {
            WSProgressHUD.showError(withStatus: "请输入您的手机号码")
            return
        }
        if   ( phoneNumTf.text!.count != 11 ||
              !( phoneNumTf.text!.starts(with: "1"))) {
            WSProgressHUD.showError(withStatus: "手机号码格式不正确")
            return
        }
        view.endEditing(true)
        // 发送他验证码
        sendSmsCode(phoneNum: phoneNumTf.text!)
    }
    
    @IBAction func loginBtnClick(_ sender: UIButton) {
        if  ( phoneNumTf.text?.count ?? 0) == 0 {
            WSProgressHUD.showError(withStatus: "请输入您的手机号码")
            return
        }
        if  ( phoneNumTf.text!.count != 11 ||
              !( phoneNumTf.text!.starts(with: "1"))) {
            WSProgressHUD.showError(withStatus: "手机号码格式不正确")
            return
        }
        
        if  (codeNumTf.text?.count ?? 0) == 0 {
            WSProgressHUD.showError(withStatus: "请输入验证码")
            return
        }
        if agreeImgV.isHighlighted == false {
            WSProgressHUD.showError(withStatus: "请选勾选用户协议和隐私政策")
            return
        }
        if (phoneNumTf.text! == "13128708140" && codeNumTf.text! == "123456" ) ||
            phoneNumTf.text! == "15810869233" && codeNumTf.text! == "kyyai@456" {
            // 账号密码登陆
            loginPwd(account: phoneNumTf.text!, pwd: codeNumTf.text!)
        }else{
            // 验证码登陆
            loginCode(account:  phoneNumTf.text!, code: codeNumTf.text!)
        }
    }
    
    
    @IBAction func agreBtnclick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            self.agreeImgV.isHighlighted = true
        }else{
            agreeImgV.isHighlighted = false
        }
        
    }
    
    @IBAction func userProtocolClick(_ sender: UIButton) {
        
        
    }
    
    @IBAction func privaceClick(_ sender: UIButton) {
        
    }
    
 
}

extension XTLoginController:UITextFieldDelegate{
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        textField.superview?.layer.borderColor = UIColor.getBase().withAlphaComponent(0.1).cgColor
        return true
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        textField.superview?.layer.borderColor = UIColor.getBase().cgColor

        return true
    }
    
}

extension XTLoginController{
    // 验证码登陆
    private  func loginCode(account:String , code: String)  {
        WSProgressHUD.show()
        let api = XTCommon.get_api_code_login()
        
        let dic = ["phonenumber": account ,"code" :  code, "iso" :"86"]
         WSProgressHUD.show()
         
        Alamofire.AF.request(api,method: .post,parameters: dic ).responseJSON { (data) in
            WSProgressHUD.dismiss()
            switch data.result {
            case .failure(_):
                WSProgressHUD.showError(withStatus: "网络请求失败，请稍后再试...")
                break
            case .success(let json):
                self.handleResult(json: json)
                break

            }
        
        }
    }
    
    
    private  func loginPwd(account:String , pwd: String)  {
        WSProgressHUD.show()
        let api = XTCommon.get_api_pwd_login()
        
        let dic = ["username": account ,"password" :  pwd]
         WSProgressHUD.show()
         
        Alamofire.AF.request(api,method: .post,parameters: dic ).responseJSON { (data) in
            WSProgressHUD.dismiss()
            switch data.result {
            case .failure(_):
                WSProgressHUD.showError(withStatus: "网络请求失败，请稍后再试...")
                break
            case .success(let json):
                self.handleResult(json: json)
                break

            }
        
        }
    }
    
    private func handleResult(json : Any){
        guard let dict = json as? [String :Any],
              let token = dict["token"] as? String else {
            WSProgressHUD.showError(withStatus: "用户名或密码错误")
            return
        }
        // 读取数据
        let username  : String = dict["username"] as? String ?? ""
        let avatar : String = dict["avatar"] as? String ?? ""
        let phonenumber : String = dict["phonenumber"] as? String ?? ""
        let role  : String = dict["role"] as? String ?? ""
        let uid : String = dict["uid"] as? String ?? ""
        let regist_date : String = dict["regist_date"] as? String ?? ""
   
        var model = XTUserModel()
        model.username = username
        model.token = token
        model.avatar = avatar
        model.phonenumber = phonenumber
        model.role = role
        model.uid = uid
        model.regist_date = regist_date
        // 保存用户数据
        XTCommon.saveUser(model)
        // 跳转到首页
        WSProgressHUD.showSuccess(withStatus: "登陆成功")
        let vc = XTVmsController()
        UIApplication.shared.keyWindow?.rootViewController = vc
    }
    
    //  dingshiqi
    private  func resetTimer()  {
        if countDownTimer != nil {
            countDownTimer?.invalidate()
        }
        countDownNum = 60
        // 创建定时器
        countDownTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(countDownAction), userInfo: nil, repeats: true)

        // 将定时器添加到当前运行循环中
        RunLoop.current.add(countDownTimer!, forMode: .common)
    }
  @objc  private  func countDownAction()  {
      countDownNum = countDownNum - 1
      if countDownNum < 0 {
          sendCodeBtn.setTitleColor(UIColor.getBase(), for: .normal)
          sendCodeBtn.isEnabled = true
          sendCodeBtn.setTitle("发送验证码", for: .normal)
      }else{
          sendCodeBtn.isEnabled = false
          sendCodeBtn.setTitle("还剩(\(countDownNum))秒", for: .normal)
          sendCodeBtn.setTitleColor(UIColor.hex("#999999"), for: .normal)
      }
    }
    
    
    private func sendSmsCode(phoneNum:String)  {
       let api = XTCommon.get_api_sms_code()
       
       
       let dic = ["phonenumber": phoneNum ]
        WSProgressHUD.show()
        
       Alamofire.AF.request(api,method: .post,parameters: dic ).responseJSON { (response) in
           WSProgressHUD.dismiss()
           WSProgressHUD.showSuccess(withStatus: "发送成功")
           self.resetTimer()
           
       
       }
       
    }
    
}
